package com.jet.chat.command;

import java.util.regex.Matcher;

import com.jet.chat.exception.ChatException;
import com.jet.chat.message.Message;
import com.jet.chat.server.ChatChannel;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;


public class ChatCommandChangeChannel extends ChatCommandAbstract {
	public ChatCommandChangeChannel() {
		super("^/\\w+\\s(\\w+)$");
	}

	@Override
	protected void executeCommand(Matcher matcher, ChatServer chatServer, ChatSession chatSession, Message chatMessage) throws ChatException {
		String channelName = matcher.group(1);
		ChatChannel chatChannel = chatServer.getChannel(channelName);
		
		if (chatChannel == null) {
			createChatChannel(chatServer, chatSession, channelName);
		} else if (channelName.equals(chatSession.getChannelName()) ) {
			remindAlreadyInChatChannel(chatSession);
		} else {
			joinToChatChannel(chatServer, chatSession, channelName, chatChannel);
		}
	}

	private void createChatChannel(ChatServer chatServer,ChatSession chatSession, String channelName) throws ChatException {
		ChatChannel chatChannel;
		chatServer.getChannel(chatSession.getChannelName()).removeSession(chatSession);
		chatChannel = new ChatChannel(channelName);
		chatServer.addChannel(chatChannel);
		chatChannel.addSession(chatSession);
		chatSession.setChannelName(channelName);
	}
	
	private void remindAlreadyInChatChannel(ChatSession chatSession) throws ChatException {
		chatSession.getQueue().addMessage("server > you are allready in");
	}
	
	private void joinToChatChannel(ChatServer chatServer, ChatSession chatSession, String channelName, ChatChannel chatChannel) throws ChatException {
		chatServer.getChannel(chatSession.getChannelName()).removeSession(chatSession);
		chatChannel.addSession(chatSession);
		chatSession.setChannelName(channelName);
	}


}
